/*
 * 版权所有：杭州领域向尚科技有限公司
 * 地址：浙江省杭州市滨江区滨安路688号天和高科技产业园5-2311
 *
 * (c) Copyright Hangzhou  Area Up Technology Co., Ltd.
 */

package org.elanfox.intellicommunity.data.base.base;


import org.elanfox.intellicommunity.data.base.dto.BaseSaveDTO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author allan
 * @date 26/10/2017
 */
public abstract class AbstractCrudService<T, ID extends Serializable> extends BaseDaoService implements CrudService<T, ID> {
    protected final JpaRepository<T, ID> repository;

    protected AbstractCrudService(JpaRepository<T, ID> repository) {
        this.repository = repository;
    }

    @Override
    public T findById(ID id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<T> findAll() {
        return repository.findAll();
    }

    @Override
    @Transactional
    public List<T> save(List<BaseSaveDTO> saveDTOS) {
        List<T> list = new ArrayList<>();
        for (BaseSaveDTO saveDTO : saveDTOS) {
            list.add(save(saveDTO));
        }

        return list;
    }

    @Override
    @Transactional
    public T save(T t) {
        return repository.save(t);
    }

    @Override
    @Transactional
    public List<T> save(Iterable<T> entities) {
        return repository.saveAll(entities);
    }

    protected String likeAll(String field) {
        return "%" + field + "%";
    }

    protected String likeLeft(String field) {
        return "%" + field;
    }

    protected String likeRight(String field) {
        return field + "%";
    }
}
